/**
 * @author Fang Lu, fanglupku@gmail.com
 * 2012-2-20
 */
package com.autotag.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.autotag.entity.Service;
import com.autotag.entity.Tag;

public class ServiceTagDao {
	private static boolean checkExist(Connection conn,
			Service service, Tag tag) {
		try {
			Statement stm = conn.createStatement();
			ResultSet rs = stm
					.executeQuery("select * from service_tag where service_id = " + service.getId() + " and tag_id = " + 
							+ tag.getId());
			if (rs.next()) {
				return true;// the user already exists
			} else {
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return true;
		}
	}
	
	public static boolean insertServiceTag(Connection conn,
			Service service, Tag tag) {
		if (tag.getName() == null) {
			return false;
		}
		if (checkExist(conn, service, tag)) {
			System.err.println("Service_Tag :" + service.getId() + "," + tag.getId()
					+ " already exists in database");
			return false;// the user already exists
		}
		try {
			
				PreparedStatement pst = conn
						.prepareStatement("insert into service_tag (service_id, tag_id, count) values (?,?,?)");
				pst.setInt(1, service.getId());
				pst.setInt(2, tag.getId());
				pst.setInt(3, 1);
				pst.executeUpdate();
				pst.close();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
